# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

import datetime
import logging

from dateutil.relativedelta import relativedelta
from odoo import api, fields, models

from . import tools

_logger = logging.getLogger(__name__)


class CrSafetyRespType(models.Model):
    _name = "cr.safety.resp.type"
    _description = "cr.safety.resp.type"

    name = fields.Char()
    code = fields.Char()


class CrSafetyRespLine(models.Model):
    _name = "cr.safety.resp.line"
    _description = "cr.safety.resp.line"

    name = fields.Char()

    state = fields.Selection([
        ('draft', '未审核'),
        # ('submit', '未审核'),
        ('done', '已审批'),
        ('cancel', '审批未通过')], default='draft')

    type_id = fields.Many2one('cr.safety.resp.type', 'type_id')
    type_code = fields.Char('type_code', related='type_id.code')
    sheet_id = fields.Many2one('cr.safety.resp.sheet', 'sheet_id', ondelete='cascade')
    employee_id = fields.Many2one('hr.employee','id',related = 'sheet.employee_id   ')
    date_month = fields.Date('date_month', related='sheet_id.date_month')
    date_month_name = fields.Char('date_month_name', related='sheet_id.date_month_name')

    employee_id = fields.Many2one('hr.employee', 'employee_id', related='sheet_id.employee_id')
    employee_name = fields.Char('employee_name', related='employee_id.name')
    employee_barcode = fields.Char('employee_barcode', related='employee_id.barcode')

    confirm_user = fields.Many2one('hr.employee', 'employee_id')
    # employee_user_id = fields.Many2one('res.users', 'employee_user_id', related='employee_id.user_id')
    confirm_user_name = fields.Char('confirm_user_name', related='confirm_user.name')

    plan = fields.Char()
    finish = fields.Char()
    plan_date = fields.Date('plan_date')
    finish_date = fields.Date('finish_date')

    # 亮点审核 写积分
    def update_state(self, state):
        def get_type_by_code(code):
            obj = self.env['cr.safety.score.input.type']
            return obj.search([['code','=', code]], limit=1).id

        if state not in ['draft','done','cancel']:
            return None

        self.state = state


        lines = self.sheet_id.line_ids.filtered(lambda ln: ln.state == 'done')
        line_len = len(lines)

        _logger.info("亮点责任数为：" + str(line_len))

        # 52, n1008, 干部“亮点工作”经相应主管审核
        type_check_by_admin = get_type_by_code('n1008')
        input_type_id = type_check_by_admin

        quantity = line_len

        obj = self.env['cr.safety.score.input']
        date_month = fields.Date.to_string(self.sheet_id.date_month)

        obj2 = obj.create({
            'employee_id': self.employee_id.id,
            'date_month': date_month,
            'input_type_id': input_type_id,
            'quantity': quantity
        })

        obj2.action_done()
        obj = obj | obj2
        return obj


class CrSafetyRespSheet(models.Model):
    _name = "cr.safety.resp.sheet"
    _description = "cr.safety.resp.sheet"

    name = fields.Char()

    date_month = fields.Date('date_month')
    date_month_name = fields.Char('date_month_name', compute='_compute_date_month')

    employee_id = fields.Many2one('hr.employee', 'employee_id')
    # employee_user_id = fields.Many2one('res.users', 'employee_user_id', related='employee_id.user_id')
    employee_name = fields.Char('employee_name', related='employee_id.name')
    employee_barcode = fields.Char('employee_barcode', related='employee_id.barcode')
    employee_job_id = fields.Many2one('hr.job', 'employee_job_id', related='employee_id.job_id')

    department_id = fields.Many2one(
        'hr.department', 'department_id',
        related='employee_id.department_id', store=True)

    line_ids = fields.One2many('cr.safety.resp.line', 'sheet_id')
    no_duty_line_ids = fields.One2many('cr.safety.resp.line', compute='_compute_no_duty_lines')
    duty_line_ids = fields.One2many('cr.safety.resp.line', compute='_compute_duty_lines')

    confirm_user = fields.Many2one('hr.employee', 'employee_id',related="employee_id.confirm_user")
    # employee_user_id = fields.Many2one('res.users', 'employee_user_id', related='employee_id.user_id')
    confirm_user_name = fields.Char('confirm_user_name', related='confirm_user.name')
    opinion = fields.Char()



    @api.depends('line_ids.type_id', 'line_ids.state')
    def _compute_no_duty_lines(self):
        for rec in self:
            lines = rec.line_ids.filtered(
                lambda line: line.type_code == 'self' and line.state == 'done')

            rec.no_duty_line_ids = lines

    @api.depends('line_ids.type_id', 'line_ids.state')
    def _compute_duty_lines(self):
        for rec in self:
            lines = rec.line_ids.filtered(
                lambda line: line.type_code == 'duty')

            rec.duty_line_ids = lines

    state = fields.Selection([
        ('draft', '未提交'),
        ('submit','待评价'),
        ('done', '已评价')], default='draft')

    state_order = fields.Char(compute='_compute_state_order',store=True)

    check_result = fields.Selection([
        ('S', '待评价'),
        ('A', '优秀'),
        ('B', '称职'),
        ('C', '基本称职'),
        ('D', '不称职')], default='S')

    @api.depends('date_month')
    def _compute_date_month(self):
        for rec in self:
            rec.date_month_name = datetime.datetime.strftime(rec.date_month, "%Y-%m")

    @api.depends('state')
    def _compute_state_order(self):
        for rec in self:
            rec.state_order = 2 if rec.state == 'draft' else 1 if rec.state == 'submint' else 3

    @api.model
    def create(self, values):
        return tools.find_or_create_for_emp_month(CrSafetyRespSheet, self, values)

    def write(self, values):
        ret = tools.write_for_emp_month(CrSafetyRespSheet, self, values)
        return ret

    # TBDCODE 责任更新预警, 预警类型
    def _update_alert(self):

        if self.check_result not in ['C', 'D']:
            return None

        # 评价为基本称职的 去预警
        alert_obj = self.env['cr.safety.alert']
        ret = alert_obj.find_or_create(
            self.date_month, self.employee_id.id, 'cr_safety.safety_alert_type_1001')

        return ret

    # TBDCODE  责任 更新 失信, 失信类型 
    def _update_lost_credit(self):
        last_month = self.date_month - relativedelta(months=+1)
        last_month = datetime.datetime.strftime(last_month, "%Y-%m") + '-1'

        # 上个月 不称职
        domain = [
            ['date_month', '=', last_month],
            ['employee_id', '=', self.employee_id.id],
            ['check_result', '=', 'D']
        ]

        obj = self.search(domain)
        if not obj:
            return None

        # 本月 不称职.  TBD, 更新到生产系统
        if self.check_result != 'D':
            return None

        type_id_ref = 'cr_safety.safety_lost_credit_type_1003'

        alert_obj = self.env['cr.safety.lost.credit']
        ret = alert_obj.find_or_create(
            self.date_month, self.employee_id.id, type_id_ref)

        return ret

    # TBDCODE 责任更新积分, 积分输入类型
    # 更新积分
    def _update_score_input(self):

        def get_type_by_result(result):
            types = {
                'A': 'n1007',
                'B': '1022',
                'C': 'n2038',
                'D': 'n2039',
            }
            obj = self.env['cr.safety.score.input.type']
            return obj.search([['code','=', types.get(result,'')]], limit=1).id

        type_A = get_type_by_result('A')
        type_B = get_type_by_result('B')
        type_C = get_type_by_result('C')
        type_D = get_type_by_result('D')

        

        result_2_score = {
            # 'S': None,
            # 'A': 'cr_safety.safety_score_input_type_1021',
            # 'B': 'cr_safety.safety_score_input_type_1022',
            # 'C': 'cr_safety.safety_score_input_type_2022',
            # 'D': 'cr_safety.safety_score_input_type_2021',

            # 4号不要了，为什么这儿出现了 4

            # 51, n1007 safety_score_input_type_1021 干部责任清单考核为优秀
            # 4,  1022     safety_score_input_type_1022 干部责任清单考核为称职
            # 96  n2038 safety_score_input_type_2022 干部责任清单考核为基本称职
            # 97  n2039 safety_score_input_type_2021 干部责任清单考核为不称职

            'S': None,
            # 2020-6-7 get id by code
            'A': type_A,
            'B': type_B,
            'C': type_C,
            'D': type_D,
            # 'A': 51,
            # 'B': 4,
            # 'C': 96,
            # 'D': 97,
            # 2020-6-7 get id by code end

            # 取 id 
        }

        obj = self.env['cr.safety.score.input']

        date_month = fields.Date.to_string(self.date_month)

        input_type_id = result_2_score.get(self.check_result)

        if not input_type_id:
            return None

        # input_type_id = self.env['ir.model.data'].xmlid_to_res_id(input_type_id_ref, True)

        obj = obj.create({
            'employee_id': self.employee_id.id,
            'date_month': date_month,
            'input_type_id': input_type_id,
            'resp_sheet_id': self.id
        })

        obj.action_done()
        return obj



    def action_draft(self):
        return self.write({'state': 'draft', 'check_result': 'S'})

    def action_submit(self):
        # for line_id in self.line_ids:
        #     # line = self.env['cr.safety.resp.line'].search([('id','=',line_id)])
        #     line_id .write({"state":"submit"})
        return self.write({'state': 'submit', 'check_result': 'S'})

    def action_done(self, check_result,opinion):
        for i in self.line_ids:
            if i.state == 'draft':
                return  {"msg":"有未审核的条目，不能进行考评！"}
        ret = self.write({'state': 'done', 'check_result': check_result,'opinion':opinion})
        self._update_score_input()
        self._update_alert()
        self._update_lost_credit()

        return ret
    def action_done2(self, check_result,opinion):
        ret = self.write({'state': 'done', 'check_result': check_result,'opinion':opinion})
        self._update_score_input()
        self._update_alert()
        self._update_lost_credit()

        return ret

    def import_resp(self):
        lines_temp = self.env["cr.safety.resp.line.temp"].search(
            [('employee_id', '=', self.employee_id.id), ('active', '=', True)])
        for i in lines_temp:
            self.write({'line_ids': [[0, 0, {'type_id': i['type_id'].id, 'plan': i['plan'], 'plan_date': i['plan_date'],
                                             'finish': i['finish'], 'finish_date': None, 'state': 'draft','confirm_user':i['confirm_user'].id}]]})


class CrSafetyRespLineTemp(models.Model):
    _name = "cr.safety.resp.line.temp"
    _description = "cr.safety.resp.line.temp"

    name = fields.Char()

    type_id = fields.Many2one('cr.safety.resp.type', 'type_id')
    type_code = fields.Char('type_code', related='type_id.code')
    active = fields.Boolean(default=True)

    employee_id = fields.Many2one('hr.employee', 'employee_id', )
    employee_name = fields.Char('employee_name', related='employee_id.name')
    employee_barcode = fields.Char('employee_barcode', related='employee_id.barcode')

    plan = fields.Char()
    finish = fields.Char()
    plan_date = fields.Date('plan_date')
    finish_date = fields.Date('finish_date')
    confirm_user = fields.Many2one('hr.employee', 'employee_id')
    # employee_user_id = fields.Many2one('res.users', 'employee_user_id', related='employee_id.user_id')
    confirm_user_name = fields.Char('confirm_user_name', related='confirm_user.name')